// ignore_for_file: must_be_immutable

import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable_for_tencent_im/flutter_slidable.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_base/tencent_im_base.dart';
import 'package:tencent_cloud_chat_uikit/base_widgets/tim_ui_kit_state.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/optimize_utils.dart';
import 'package:tencent_cloud_chat_uikit/ui/widgets/avatar.dart';
import 'package:tencent_cloud_chat_uikit/ui/widgets/az_list_view.dart';
import 'package:tencent_cloud_chat_uikit/ui/widgets/radio_button.dart';
import 'package:tencent_cloud_chat_uikit/base_widgets/tim_ui_kit_base.dart';

class GroupProfileMemberList extends StatefulWidget {
  GroupProfileMemberList({
    Key? key,
    required this.memberList,
    this.onlineMemberIds = const {},
    this.showOnlineStatus = false,
    this.groupType,
    this.removeMember,
    this.canSlideDelete = true,
    this.canSelectMember = false,
    this.canAtAll = false,
    this.singleSelect = false,
    this.onSelectedMemberChange,
    this.onTapMemberItem,
    this.customTopArea,
    this.touchBottomCallBack,
    this.maxSelectNum,
  }) : super(key: key);

  final List<V2TimGroupMemberFullInfo?> memberList;
  final Function(String userID)? removeMember;
  final bool canSlideDelete;
  final bool canSelectMember;
  final bool canAtAll;
  final bool singleSelect;

  // when the @ need filter some group types
  final String? groupType;
  final Function(List<V2TimGroupMemberFullInfo> selectedMember)? onSelectedMemberChange;

  // notice: onTapMemberItem and onSelectedMemberChange use together will triger together
  final Function(V2TimGroupMemberFullInfo memberInfo)? onTapMemberItem;

  // When sliding to the bottom bar callBack
  final Function()? touchBottomCallBack;

  final int? maxSelectNum;

  final Set<String> onlineMemberIds;

  final bool showOnlineStatus;

  Widget? customTopArea;

  @override
  State<StatefulWidget> createState() => _GroupProfileMemberListState();
}

class _GroupProfileMemberListState extends TIMUIKitState<GroupProfileMemberList> {
  List<V2TimGroupMemberFullInfo> selectedMember = [];

  _getShowName(V2TimGroupMemberFullInfo? item) {
    final nameCard = item?.nameCard ?? "";
    final nickName = item?.nickName ?? "";
    return nameCard.isNotEmpty
        ? nameCard
        : nickName;
  }

  List<ISuspensionBeanImpl> _getShowList(List<V2TimGroupMemberFullInfo?> memberList) {
    final List<ISuspensionBeanImpl> showList = List.empty(growable: true);
    for (var i = 0; i < memberList.length; i++) {
      final item = memberList[i];
      final showName = _getShowName(item);
      if (item?.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_OWNER ||
          item?.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_ADMIN) {
        showList.add(ISuspensionBeanImpl(
            memberInfo: item, tagIndex: "@", isOwner: item?.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_OWNER));
      } else {
        String pinyin = PinyinHelper.getPinyinE(showName);
        String tag = pinyin.substring(0, 1).toUpperCase();
        if (RegExp("[A-Z]").hasMatch(tag)) {
          showList.add(ISuspensionBeanImpl(memberInfo: item, tagIndex: tag));
        } else {
          showList.add(ISuspensionBeanImpl(memberInfo: item, tagIndex: "#"));
        }
      }
    }

    SuspensionUtil.sortListBySuspensionTag(showList);
    final int ownerIndex = showList.indexWhere((e) => e.isOwner);
    if (ownerIndex > 0) {
      final bean = showList.removeAt(ownerIndex);
      showList.insert(0, bean);
    }

    // add @everyone item
    if (widget.canAtAll) {
      final canAtGroupType = ["Work", "Public", "Meeting"];
      if (canAtGroupType.contains(widget.groupType)) {
        showList.insert(
          0,
          ISuspensionBeanImpl(
            memberInfo: V2TimGroupMemberFullInfo(
              userID: "__kImSDK_MesssageAtALL__",
              nickName: TIM_t("所有人"),
            ),
            tagIndex: "#",
          ),
        );
      }
    }

    return showList;
  }

  Widget _buildListItem(BuildContext context, V2TimGroupMemberFullInfo memberInfo) {
    final theme = Provider.of<TUIThemeViewModel>(context).theme;
    final isGroupMember = memberInfo.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_MEMBER;
    return Container(
      color: Colors.white,
      child: Slidable(
        endActionPane: widget.canSlideDelete && isGroupMember
            ? ActionPane(motion: const DrawerMotion(), children: [
                SlidableAction(
                  onPressed: (_) {
                    if (widget.removeMember != null) {
                      widget.removeMember!(memberInfo.userID);
                    }
                  },
                  flex: 1,
                  backgroundColor: theme.cautionColor ?? CommonColor.cautionColor,
                  autoClose: true,
                  label: TIM_t("删除"),
                )
              ])
            : null,
        child: Column(
          children: [
            GestureDetector(
              onTap: () {
                if (widget.onTapMemberItem != null) {
                  widget.onTapMemberItem!(memberInfo);
                }
                if (widget.canSelectMember) {
                  final isChecked = selectedMember.contains(memberInfo);
                  if (isChecked) {
                    selectedMember.remove(memberInfo);
                    setState(() {});
                  } else {
                    // 单选模式
                    if (widget.singleSelect) {
                      selectedMember.clear();
                      selectedMember.add(memberInfo);
                      widget.onSelectedMemberChange?.call(selectedMember);
                      setState(() {});
                      return;
                    }
                    // 限制最大选择数模式
                    if (widget.maxSelectNum != null) {
                      if (selectedMember.length < widget.maxSelectNum!) {
                        selectedMember.add(memberInfo);
                        widget.onSelectedMemberChange?.call(selectedMember);
                        setState(() {});
                      }
                      return;
                    }
                    selectedMember.add(memberInfo);
                    widget.onSelectedMemberChange?.call(selectedMember);
                    setState(() {});
                  }
                }
              },
              child: Container(
                color: Colors.white,
                height: 62,
                padding: const EdgeInsets.symmetric(horizontal: 17),
                child: Row(
                  children: [
                    if (widget.canSelectMember)
                      Container(
                        margin: const EdgeInsets.only(right: 10),
                        child: CheckBoxButton(
                          onlyShow: true,
                          isChecked: selectedMember.contains(memberInfo),
                        ),
                      ),
                    Container(
                      width: 36,
                      height: 36,
                      margin: const EdgeInsets.only(right: 8),
                      child: Avatar(
                        faceUrl: memberInfo.faceUrl ?? "",
                        showName: _getShowName(memberInfo),
                        onlineStatus: widget.showOnlineStatus
                            ? V2TimUserStatus(
                                statusType: widget.onlineMemberIds.contains(memberInfo.userID) ? 1 : 2,
                              )
                            : null,
                        type: 1,
                      ),
                    ),
                    Flexible(
                      child: Text(
                        _getShowName(memberInfo),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                          fontSize: 15,
                          color: Color(0xFF1D2541),
                        ),
                      ),
                    ),
                    memberInfo.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_OWNER
                        ? Container(
                            margin: const EdgeInsets.only(left: 5),
                            child: Text(
                              TIM_t("群主"),
                              style: const TextStyle(color: Colors.white, fontSize: 11, height: 1.25),
                            ),
                            padding: const EdgeInsets.fromLTRB(7, 1.5, 7, 1.5),
                            decoration: const BoxDecoration(
                              color: Color(0xFF1972FF),
                              borderRadius: BorderRadius.all(Radius.circular(8.5)),
                            ),
                          )
                        : memberInfo.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_ADMIN
                            ? Container(
                                margin: const EdgeInsets.only(left: 5),
                                child: Text(
                                  TIM_t("管理员"),
                                  style: const TextStyle(color: Colors.white, fontSize: 11, height: 1.25),
                                ),
                                padding: const EdgeInsets.fromLTRB(7, 1.5, 7, 1.5),
                                decoration: const BoxDecoration(
                                  color: Color(0xFF1972FF),
                                  borderRadius: BorderRadius.all(Radius.circular(8.5)),
                                ),
                              )
                            : Container(),
                    if (memberInfo.customInfo?["Tag"]?.isNotEmpty ?? false)
                      Container(
                        margin: const EdgeInsets.only(left: 5),
                        padding: const EdgeInsets.fromLTRB(7, 1.5, 7, 1.5),
                        decoration: const BoxDecoration(
                          color: Color(0xFF1972FF),
                          borderRadius: BorderRadius.all(Radius.circular(8.5)),
                        ),
                        child: Text(
                          memberInfo.customInfo!["Tag"]!,
                          style: const TextStyle(
                            overflow: TextOverflow.ellipsis,
                            color: Colors.white,
                            fontSize: 11,
                            height: 1.25,
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
            const Divider(thickness: 0.5, indent: 61, endIndent: 0, color: Color(0xFFEEEFF3), height: 0.5)
          ],
        ),
      ),
    );
  }

  static Widget getSusItem(BuildContext context, TUITheme theme, String tag, {double susHeight = 40}) {
    if (tag == '@') {
      tag = TIM_t("群主、管理员");
    }
    return Container(
      height: susHeight,
      width: MediaQuery.of(context).size.width,
      padding: const EdgeInsets.only(left: 17.0),
      color: Colors.white,
      alignment: Alignment.bottomLeft,
      child: Text(
        tag,
        softWrap: true,
        style: const TextStyle(
          fontSize: 14.0,
          color: Color(0xFF7C8191),
        ),
      ),
    );
  }

  @override
  Widget tuiBuild(BuildContext context, TUIKitBuildValue value) {
    final TUITheme theme = value.theme;

    final throttleFunction = OptimizeUtils.throttle((ScrollNotification notification) {
      final pixels = notification.metrics.pixels;
      // 总像素高度
      final maxScrollExtent = notification.metrics.maxScrollExtent;
      // 滑动百分比
      final progress = pixels / maxScrollExtent;
      if (progress >= 0.9 && widget.touchBottomCallBack != null) {
        widget.touchBottomCallBack!();
      }
    }, 300);
    final showList = _getShowList(widget.memberList);
    return Container(
      color: Colors.white,
      child: SafeArea(
        child: Column(
          children: [
            widget.customTopArea != null ? widget.customTopArea! : Container(),
            const Divider(),
            Expanded(
              child: NotificationListener<ScrollNotification>(
                onNotification: (ScrollNotification notification) {
                  throttleFunction(notification);
                  return true;
                },
                child: (showList.isEmpty)
                    ? Center(
                        child: Text(TIM_t("暂无群成员")),
                      )
                    : AZListViewContainer(
                        susColor: Colors.white,
                        memberList: showList,
                        susItemBuilder: (context, index) {
                          final model = showList[index];
                          return getSusItem(context, theme, model.getSuspensionTag());
                        },
                        itemBuilder: (context, index) {
                          final memberInfo = showList[index].memberInfo as V2TimGroupMemberFullInfo;

                          return _buildListItem(context, memberInfo);
                        },
                      ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
